package com.aspirecn.core.datacache.useragent;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

//import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;

import com.aspire.core.match.ua.object.DeviceBrand;
import com.aspirecn.core.commons.Configuration;
import com.aspirecn.core.datacache.BaseLocalCache;
import com.csvreader.CsvReader;

/**
 * deviceos数据缓存
 * 
 * @author wangxinning
 * 
 */
public class DeviceBrandCache extends BaseLocalCache {

	public final static Logger logger = Logger.getLogger(DeviceBrandCache.class);

	private Map<Integer, DeviceBrand> deviceBrandMap = new HashMap<Integer, DeviceBrand>();

	private static DeviceBrandCache instance = new DeviceBrandCache();

	private DeviceBrandCache() {

		this.dataFile = new File(Configuration.getInstance()
				.getDownloadFilePath() + File.separator + "uaV3" + File.separator + "devicebrand.csv");
		load();
	}

	public static DeviceBrandCache getInstance() {
		return instance;
	}

	public void load() {

		if (!loading.getAndSet(true)
				&& Configuration.getInstance().switchUACache() && this.dataFile.exists()) {

			long start = System.currentTimeMillis();

			try {
				
				CsvReader reader = new CsvReader(this.dataFile.toString(), ',',
						Charset.forName("gbk"));

				while (reader.readRecord()) {

					if( reader.getCurrentRecord() == 0 )//设置列名
		    		{
		    			reader.setHeaders(reader.getValues());
		    		}
		    		else
		    		{
		    			DeviceBrand brand = new DeviceBrand();
		    			brand.setBrand_id(NumberUtils.toInt(reader.get("BRAND_ID")));
		    			brand.setBrand_name(StringUtils.remove(reader.get("BRAND_NAME"),"(null)"));
		    			brand.setEnglish_brand_name(StringUtils.remove(reader.get("ENGLISH_BRAND_NAME"),"(null)"));
		    			brand.setBrand_desc(StringUtils.remove(reader.get("BRAND_DESC"),"(null)"));
		    			
		    			deviceBrandMap.put(brand.getBrand_id(), brand);
		    		}
				}
				
				reader.close();

			} catch (Exception e) {
				logger.error("DeviceBrand信息加载异常", e);
			}

			loading.set(false);
			long end = System.currentTimeMillis();
			updateFileDownloadTime();
			logger.info("DeviceBrand信息加载完成，time=" + (end - start) + "ms,size="
					+ deviceBrandMap.size());

		} else {
			loading.set(false);
			logger.info("配置关闭，DeviceBrand信息未加载");
		}
		
		loading.set(false);
	}

	@Override
	public void clear() {

		deviceBrandMap.clear();
	}

	@Override
	public void reload() {

		if (this.fileIsChange()) {
			this.load();
		} else {
			logger.info("没变化，DeviceBrand信息未加载");
		}
	}	
	
	public DeviceBrand getDeviceBrand( int brandid )
	{
		//return this.deviceBrandMap.get(brandid);		
		DeviceBrand brand = this.deviceBrandMap.get(brandid);
//		if( brand != null )
//		{			
//			try {
//				brand = (DeviceBrand)BeanUtils.cloneBean(brand);
//			} catch (Exception e) {
//				logger.error("clone品牌数据异常", e);
//			}
//		}
		
		return brand;
	}
	
	/**
	 * 搜索品牌
	 * @param keyword
	 * @return
	 */
	public List<DeviceBrand> searchBrand( String keyword )
	{
		List<DeviceBrand> list = new ArrayList<DeviceBrand>();
		
		Iterator<Integer> keyIte = deviceBrandMap.keySet().iterator();
		
		while( keyIte.hasNext() )
		{
			Integer keyInt = keyIte.next();
			DeviceBrand tempDeviceBrand = deviceBrandMap.get(keyInt);
			
			if (tempDeviceBrand != null && StringUtils.containsIgnoreCase(tempDeviceBrand.toString(), keyword)) {
				list.add(tempDeviceBrand);
			}			
		}

		return list;
	}
	
	
	public List<DeviceBrand> getDeviceBrandList()
	{
		List<DeviceBrand> list = new ArrayList<DeviceBrand>();
		
		Iterator<Integer> keyIte = deviceBrandMap.keySet().iterator();
		
		while( keyIte.hasNext() )
		{
			Integer keyInt = keyIte.next();
			DeviceBrand tempDeviceBrand = deviceBrandMap.get(keyInt);
			
			if (tempDeviceBrand != null) {
				list.add(tempDeviceBrand);
			}			
		}

		return list;
	}
	
	public static void main(String[] args) {
		DeviceBrandCache geoCache = DeviceBrandCache.getInstance();
		System.out.println(geoCache.getDeviceBrand(745));
	}
}